package com.ty.dao.impl;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ty.dao.StudentDao;
import com.ty.entity.Student;
import com.ty.utils.JDBCUtils;

public class StudentDaoImpl implements StudentDao {

    @Override
    public void addStudent(Student student) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始添加学生：" + student.getStudentId());
            String sql = "INSERT INTO student (name, age, major_id, phone, student_id) VALUES (?, ?, ?, ?, ?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, student.getName());
            ps.setInt(2, student.getAge());
            ps.setInt(3, student.getMajorId());
            ps.setString(4, student.getPhone());
            ps.setString(5, student.getStudentId());
            ps.executeUpdate();
            JDBCUtils.logOperation("INSERT", "student", "Add student with student_id: " + student.getStudentId());
            System.out.println("[DB LOG] 添加成功：" + student.getStudentId());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("添加学生失败", e);
        } finally {
            JDBCUtils.close(null, ps, conn);
        }
    }

    @Override
    public void deleteStudent(int id) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始删除学生：" + id);
            String sql = "DELETE FROM student WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ps.executeUpdate();
            JDBCUtils.logOperation("DELETE", "student", "Delete student with id: " + id);
            System.out.println("[DB LOG] 删除成功：" + id);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("删除学生失败", e);
        } finally {
            JDBCUtils.close(null, ps, conn);
        }
    }

    @Override
    public void updateStudent(Student student) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始更新学生：" + student.getId());
            String sql = "UPDATE student SET name = ?, age = ?, major_id = ?, phone = ?, student_id = ? WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, student.getName());
            ps.setInt(2, student.getAge());
            ps.setInt(3, student.getMajorId());
            ps.setString(4, student.getPhone());
            ps.setString(5, student.getStudentId());
            ps.setInt(6, student.getId());
            ps.executeUpdate();
            JDBCUtils.logOperation("UPDATE", "student", "Update student with id: " + student.getId());
            System.out.println("[DB LOG] 更新成功：" + student.getId());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("更新学生失败", e);
        } finally {
            JDBCUtils.close(null, ps, conn);
        }
    }

    @Override
    public Map<String, Object> getStudentById(int id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始查询学生：" + id);
            String sql = "SELECT * FROM student WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            JDBCUtils.logOperation("SELECT", "student", "Query student by id: " + id);
            if (rs.next()) {
                Map<String, Object> student = new HashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(i);
                    student.put(columnName, value);
                }
                return student;
            }
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询学生失败", e);
        } finally {
            JDBCUtils.close(rs, ps, conn);
        }
    }

    @Override
    public List<Map<String, Object>> getAllStudents() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> students = new ArrayList<>();

        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始查询所有学生");
            String sql = "SELECT * FROM student ORDER BY id";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            JDBCUtils.logOperation("SELECT", "student", "Query all students");
            while (rs.next()) {
                Map<String, Object> student = new HashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(i);
                    student.put(columnName, value);
                }
                students.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询所有学生失败", e);
        } finally {
            JDBCUtils.close(rs, ps, conn);
        }
        return students;
    }

    @Override
    public List<Map<String, Object>> getStudentsByName(String name) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> students = new ArrayList<>();

        try {
            conn = JDBCUtils.getConnection();
            System.out.println("[DB LOG] 开始按名称查询学生：" + name);
            String sql = "SELECT * FROM student WHERE name LIKE ? ORDER BY id";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "%" + name + "%");
            rs = ps.executeQuery();
            JDBCUtils.logOperation("SELECT", "student", "Query students by name: " + name);
            while (rs.next()) {
                Map<String, Object> student = new HashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnLabel(i);
                    Object value = rs.getObject(i);
                    student.put(columnName, value);
                }
                students.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("按名称查询学生失败", e);
        } finally {
            JDBCUtils.close(rs, ps, conn);
        }
        return students;
    }
}